const http = require('http');
const fs = require('fs');

let io = require('socket.io');

let user = {
    name: '石兴龙',
    balance: '100.00'
}

let data = {
    success: true,
    msg: '',
    data: {
        name: '石兴龙',
        balance: '100.00'
    }
}

let getOrderList = {
    success: true,
    msg: '',
    data: [
        '订单1',
        '订单2',
        '订单3',
    ]
}

let getBalance = {
    success: true,
    msg: '',
    data: {
        balance: '100.00'
    }
}

const server = http.createServer((req, res) => {
    
    res.setHeader('Access-Control-Allow-Origin', '*')
    res.setHeader('Access-Control-Allow-Methods', 'POST')
    res.setHeader('Access-Control-Allow-Headers', 'Content-Type')

    // 静态资源处理
    if (/.(html|js)$/.test(req.url)) {
        let filePath = __dirname + '/' + req.url
        if (fs.existsSync(filePath)) {
            res.writeHead(200);
            fs.createReadStream(filePath).pipe(res)
        }
    } else if (req.method === 'POST') {

        res.setHeader('Content-Type', 'application/json; charset=utf-8')

        if (req.url === '/loginUser') {
            res.end(JSON.stringify(data))
        } else if (req.url === '/login') {
            setTimeout(() => {
                res.end(JSON.stringify(data))
            }, 500)
        } else if (req.url === '/getOrderList') {
            res.end(JSON.stringify(getOrderList))
        } else if (req.url === '/getBalance') {
            res.end(JSON.stringify(getBalance))
        } 
    } else {
        res.statusCode = 200
        res.end('404');
    }
})

io = io(server)

let clientList = []

io.on('connection', client => {
    client.name = 'client-' + Date.now();
    clientList.push(client);

    console.log(
        'connection 当前用户总数: ', clientList.length
    )

    client.emit('action-start', client.name)

    // 用户发言
    client.on('action-senMsg', data => { 
        io.emit('user-msg', {
            name: client.name,
            msg: data
        })
    });
    // 用户第一次连接, 发送name
    client.emit('action-connection', client.name)

    // 用户离开
    client.on('disconnect', () => { 
        let index = clientList.indexOf(client)
        clientList.splice(index, 1);
        console.log('用户离开', index)
        console.log(
            'disconnect 当前用户总数: ', clientList.length
        )
    });
});

server.listen(3002, () => {
    console.log('server is runing localhost:3002')
})
